<template>
  <el-dialog title="添加灭治部位" :visible.sync="dialogVisible" width="35%">
    <div class="formBox">
      <div class="table-header">
        <el-button type="primary" size="small" @click="addRow">新增</el-button>
      </div>
      <el-table :data="localAreaTableData" border style="width: 100%">
        <el-table-column
          prop="area"
          label="灭治部位"
          min-width="200"
          align="center"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.area"
              size="small"
              placeholder="请输入灭治部位"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="count"
          label="灭治点位数"
          min-width="200"
          align="center"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.count"
              size="small"
              placeholder="请输入点位数"
              @input="onDecimalInput($event, scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              :style="{
                color: localAreaTableData.length <= 1 ? '#c0c4cc' : '#f56c6c',
              }"
              :disabled="localAreaTableData.length <= 1"
              @click="deleteRow(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: "AddAreaDialog",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    // 使用 .sync 同步父组件的数组
    areaTableData: {
      type: Array,
      default: () => [{ area: "", count: "" }],
    },
  },
  data() {
    return {
      localAreaTableData: this.cloneRows(this.areaTableData),
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
  watch: {
    areaTableData: {
      deep: true,
      handler(newVal) {
        this.localAreaTableData = this.cloneRows(newVal);
      },
    },
    value(val) {
      if (val) {
        // 打开时刷新本地数据，避免旧缓存
        this.localAreaTableData = this.cloneRows(this.areaTableData);
      }
    },
  },
  methods: {
    cloneRows(rows) {
      return (rows || []).map((r) => ({
        area: r.area || "",
        count: r.count || "",
      }));
    },
    addRow() {
      if (this.localAreaTableData.length > 0) {
        const last =
          this.localAreaTableData[this.localAreaTableData.length - 1];
        if (!last.area || !last.count) {
          this.$message.warning("请先完善上一项的信息");
          return;
        }
      }
      this.localAreaTableData.push({ area: "", count: "" });
    },
    deleteRow(index) {
      if (this.localAreaTableData.length <= 1) {
        this.$message.warning("至少需要保留一项");
        return;
      }
      this.localAreaTableData.splice(index, 1);
    },
    onDecimalInput(value, row) {
      let cleanValue = String(value).replace(/[^\d.]/g, "");
      if (
        cleanValue.startsWith("0") &&
        cleanValue.length > 1 &&
        !cleanValue.startsWith("0.")
      ) {
        cleanValue = cleanValue.substring(1);
      }
      const parts = cleanValue.split(".");
      if (parts.length > 2)
        cleanValue = parts[0] + "." + parts.slice(1).join("");
      if (parts.length === 2 && parts[1].length > 2)
        cleanValue = parts[0] + "." + parts[1].substring(0, 2);
      row.count = cleanValue;
    },
    onCancel() {
      this.dialogVisible = false;
      this.$emit("cancel");
    },
    onSubmit() {
      for (let i = 0; i < this.localAreaTableData.length; i++) {
        const r = this.localAreaTableData[i];
        if (!r.area || !r.count) {
          this.$message.error(`第${i + 1}项信息填写不完整，请检查`);
          return;
        }
      }
      // 同步到父组件
      this.$emit(
        "update:areaTableData",
        this.cloneRows(this.localAreaTableData),
      );
      this.$emit("submit", this.cloneRows(this.localAreaTableData));
      this.dialogVisible = false;
      this.$message.success("保存成功");
    },
  },
};
</script>

<style lang="scss" scoped>
.table-header {
  margin-bottom: 15px;
  text-align: left;
}
</style>
